package proxy

import (
	"fmt"
	"sync"
	"time"
)

// 性能监测代码

type MonitoringProxy struct {
	realService Service
	metrics     map[string]*Metrics
	mu          sync.Mutex
}

func NewMonitoringProxy(realService Service) *MonitoringProxy {
	return &MonitoringProxy{
		realService: realService,
		metrics:     make(map[string]*Metrics),
	}
}

type Metrics struct {
	count    int
	duration time.Duration
	avg      float64
}

func (p *MonitoringProxy) HandleRequest(url, method string) (int, string) {
	start := time.Now()
	status, response := p.realService.HandleRequest(url, method)
	duration := time.Since(start)
	key := fmt.Sprintf("%s:%s", url, method)

	p.mu.Lock()
	defer p.mu.Unlock()
	if metric, ok := p.metrics[key]; ok {
		metric.count++
		metric.duration += duration
		metric.avg = float64(metric.duration) / float64(metric.count)
	} else {
		p.metrics[key] = &Metrics{
			count:    1,
			duration: duration,
			avg:      float64(duration),
		}
	}
	return status, response
}

func (p *MonitoringProxy) GetMetrics() map[string]*Metrics {
	return p.metrics
}
